package com.example.lib_widget.redpacket;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.example.lib_widget.AutoSizeUtils;
import com.example.lib_widget.R;

/**
 * @author yaotianxue
 * @description
 * @date 2025/2/28
 */
public class RedPacketView extends View {
    public static final String TAG = "RedPacketView";

    private Context context;
    private Paint bgPaint;
    private Paint fgPaint;
    private Paint bitmapPaint;
    private int strokeWidth;//粗细
    //圆弧范围
    private RectF rectF = null;
    //图片范围
    private Rect bitmapRect = null;
    private Rect bitmapDstRect = null;
    //图片
    private Bitmap bitmap = null;

    /**
     * 默认宽高
     */
    private int defaultWidth;
    private int defaultHeight;


    private int angle = 0; //扫描弧度

    public RedPacketView(Context context) {
        this(context, null);
    }

    public RedPacketView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RedPacketView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        this(context, attrs, defStyleAttr, 0);
    }

    public RedPacketView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        this.context = context;
        //画笔
        initPaint();
    }
    private ValueAnimator valueAnimator;
    //接口回调
    private Callback callback=null;
    public void setCallback(Callback callback) {
        this.callback = callback;
    }

    public interface Callback{
        void start();
        void pause(int angle);
        void resume();
        void completed();
        void cancel();
    }

    /**
     * 开始动画
     */
    public void startAnim(){
        valueAnimator = ValueAnimator.ofInt(0,360);
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(@NonNull ValueAnimator animation) {
                angle = (int) animation.getAnimatedValue();
                //刷新view --》onDraw
                invalidate();
            }
        });
        valueAnimator.addPauseListener(new AnimatorListenerAdapter(){
            @Override
            public void onAnimationPause(@NonNull Animator animation) {
                super.onAnimationPause(animation);
                if(callback != null){
                    callback.pause(angle);
                }
            }

            @Override
            public void onAnimationResume(Animator animation) {
                super.onAnimationResume(animation);
                if(callback != null){
                    callback.resume();
                }
            }
        });

        valueAnimator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
                if(callback != null){
                    callback.start();
                }
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                if(callback != null){
                    angle = 0;
                    invalidate();
                    callback.completed();
                }
            }

            @Override
            public void onAnimationCancel(Animator animation) {
                super.onAnimationCancel(animation);
                if(callback != null){
                    angle = 0;
                    invalidate();
                    callback.cancel();
                }
            }
        });
        valueAnimator.setDuration(10*1000);
        valueAnimator.start();
    }

    /**
     * 暂停
     */

    public void pauseAnim(){
        if(valueAnimator != null && valueAnimator.isRunning()){
            valueAnimator.pause();
        }
    }
    /**
     * 恢复
     */
    public void resumeAnim(){
        if(valueAnimator != null ){
            valueAnimator.resume();
        }
    }

    /**
     * 取消
     */
    public void cancelAnim(){
        if(valueAnimator != null && valueAnimator.isRunning()){
            valueAnimator.cancel();
            valueAnimator = null;
        }
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if(null != bitmap){
            bitmap.recycle();
            bitmap = null;
        }
    }

    @Override
    protected void onDraw(@NonNull Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawBitmap(bitmap,bitmapRect,bitmapDstRect,bitmapPaint); //绘制图片
        canvas.drawArc(rectF,0,360,false,bgPaint); //绘制背景圆环
        canvas.drawArc(rectF,-90,angle,false,fgPaint); //绘制前景圆环
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //宽度
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        //高度
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        if(widthMode == MeasureSpec.AT_MOST && heightMode == MeasureSpec.AT_MOST){
            setMeasuredDimension(defaultWidth,defaultHeight);
        }else if(widthMode == MeasureSpec.AT_MOST){
            setMeasuredDimension(defaultWidth,heightSize);
        }else if(heightMode == MeasureSpec.AT_MOST){
            setMeasuredDimension(widthSize,defaultHeight);
        }
    }

    /**
     * 尺寸改变
     */
    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        //bitmap
        bitmap = getBitmap(R.drawable.redpacket,getMeasuredWidth()/2,getMeasuredHeight()/2);
        //图片范围
        bitmapRect = new Rect(0,0,bitmap.getWidth(),bitmap.getHeight()); //大小范围
        bitmapDstRect = new Rect(getMeasuredWidth()/2- bitmap.getWidth()/2,getMeasuredHeight()/2-bitmap.getHeight()/2,
                getMeasuredWidth()/2+bitmap.getWidth()/2,getMeasuredHeight()/2 +bitmap.getHeight()/2); //位置范围
        //圆环范围
        rectF = new RectF(strokeWidth,strokeWidth,getMeasuredWidth()-strokeWidth,getMeasuredHeight()-strokeWidth);
    }

    /**
     * 图片二次采样
     * @param id
     * @param width
     * @param height
     * @return
     */
    private Bitmap getBitmap(int id,int width,int height){
        //尺寸压缩
        //第一次采样
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        BitmapFactory.decodeResource(getResources(),id,options);
        //计算压缩比例
        int outWidth = options.outWidth;
        int outHeight = options.outHeight;
        int size = 1;
        while (outWidth/size > width || outHeight/size > height){
            size *= 2;
        }
        //第二次按照压缩比例采样
        options.inJustDecodeBounds = false;
        options.inSampleSize = size;
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), id, options);
        return bitmap;

    }

    private void initPaint(){
        strokeWidth = AutoSizeUtils.INSTANCE.dpToPx(context,5);
        defaultWidth = AutoSizeUtils.INSTANCE.dpToPx(context,60);
        defaultHeight = AutoSizeUtils.INSTANCE.dpToPx(context,60);

        //灰色背景圆环
        bgPaint = new Paint();
        bgPaint.setAntiAlias(true);
        bgPaint.setDither(true);
        bgPaint.setColor(Color.rgb(221,221,221));
        bgPaint.setStrokeWidth(strokeWidth);
        bgPaint.setStyle(Paint.Style.STROKE);
        //红色前景圆环
        fgPaint = new Paint();
        fgPaint.setAntiAlias(true);
        fgPaint.setDither(true);
        fgPaint.setColor(Color.rgb(255,0,0));
        fgPaint.setStrokeWidth(strokeWidth);
        fgPaint.setStyle(Paint.Style.STROKE);
        //图片画笔
        bitmapPaint = new Paint();
        bitmapPaint.setAntiAlias(true);
        bitmapPaint.setDither(true);


    }

}
